package data.set.implementation;

import java.util.ArrayList;
import java.util.Iterator;

import data.set.OfflineSet;
import data.set.OfflineSetIterator;
import data.set.adaptator.Iterator_FromOfflineSetIterator;


/**
 * Builds an offline set which is a sampling of an other set
 * @author denoyer
 *
 */
public class OfflineSetSampling<X> implements OfflineSet<X>
{
	private OfflineSet<X> set;
	private ArrayList<Integer> ids;

	
	/**
	 * 
	 * @param set the input set
	 * @param rating the rate of documents to keep (>0). Note that this value can be >1
	 */
	public OfflineSetSampling(OfflineSet<X> set,double rating)
	{
		//Log.sendMessage("info", this.getClass().getName(),"Building sampling set");
		this.set=set;
		ids=new ArrayList<Integer>();
		OfflineSetIterator<X> it=set.inputsetiterator();
		while(it.hasNext())
		{			
			it.next();
			double tirage=Math.random();
			if (tirage<rating)
				ids.add(it.getCurrentId());
		}		
	}

	
	
	public long size() {
		return(ids.size());
	}

	
	public X getObject(int id) {
		if (ids.contains(id))
			return(set.getObject(id));
		return null;
	}

	
	public OfflineSetIterator<X> inputsetiterator() {
		return new IT(set,ids);
	}

	
	public Iterator<X> iterator() {
		return new Iterator_FromOfflineSetIterator<X>(inputsetiterator());
	}
	

	private class IT implements OfflineSetIterator<X>
	{
		private OfflineSet<X> set;
		private ArrayList<Integer> ids;
		private int current_index;
		
		public IT(OfflineSet<X> set,ArrayList<Integer> ids)
		{
			this.set=set;
			this.ids=ids;
			current_index=-1;
		}
				
		
		public int getCurrentId() {
			return ids.get(current_index);
		}

		
		public X getCurrentObject() {
			return set.getObject(ids.get(current_index));
		}

		
		public boolean hasNext() {
			return (current_index <ids.size()-1);
		}

		
		public void next() {
			current_index++;
		}
	}

}
